﻿using Abp.Domain.Repositories;
using Abp.Domain.Services;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace shenghua.Common.FreeValues
{
    public class FreeValueManager: DomainService
    {
        private readonly IRepository<FreeValue> _freeValueRepository;

        public FreeValueManager(
            IRepository<FreeValue> freeValueRepository)
        {
            _freeValueRepository = freeValueRepository;
        }

        public string GetValue(string keyName, string defaultValue = "")
        {
            FreeValue freeValue = _freeValueRepository.GetAll().Where(r => r.KeyName == keyName).FirstOrDefault();
            if (freeValue == null)
            {
                return defaultValue;
            }
            else
            {
                return freeValue.Value;
            }
        }

        public async Task<FreeValue> SetValue(string keyName, string value)
        {
            FreeValue freeValue = await _freeValueRepository.FirstOrDefaultAsync(r => r.KeyName == keyName);
            var json = value;

            if (freeValue == null)
            {
                freeValue = new FreeValue
                {
                    KeyName = keyName,
                    Value = json
                };
                await _freeValueRepository.InsertAndGetIdAsync(freeValue);
            }
            else
            {
                freeValue.Value = json;
            }

            return freeValue;
        }

        public T GetValue<T>(string keyName, T defaultValue)
        {
            FreeValue freeValue = _freeValueRepository.GetAll().Where(r => r.KeyName == keyName).FirstOrDefault();
            if (freeValue == null)
            {
                return defaultValue;
            }
            else
            {
                return JsonConvert.DeserializeObject<T>(freeValue.Value);
            }
        }

        public async Task<FreeValue> SetValue<T>(string keyName, T value)
        {
            FreeValue freeValue = await _freeValueRepository.FirstOrDefaultAsync(r => r.KeyName == keyName);
            var json = JsonConvert.SerializeObject(value);

            if (freeValue == null)
            {
                freeValue = new FreeValue
                {
                    KeyName = keyName,
                    Value = json
                };
                await _freeValueRepository.InsertAndGetIdAsync(freeValue);
            }
            else
            {
                freeValue.Value = json;
            }

            return freeValue;
        }
    }
}
